import {
  type RouteRecordRaw,
  createRouter,
  createWebHistory,
} from 'vue-router';

const fixedModules = import.meta.webpackContext('./modules', {
  recursive: true,
  regExp: /\.ts$/,
});
// 3️⃣ 读取每个模块的 default 导出，并拼成一个扁平的 routes 数组
const fixedRouterList = mapModuleRouterList(fixedModules);

const defaultRouterList = [];

export const allRoutes = [...defaultRouterList, ...fixedRouterList];
// 固定路由模块转换为路由
export function mapModuleRouterList(modules: Rspack.Context) {
  const routerList: RouteRecordRaw[] = modules.keys().flatMap((file) => {
    const mod = fixedModules(file) as { default: RouteRecordRaw[] };
    return mod.default;
  });
  return routerList;
}

console.log(allRoutes);
const router = createRouter({
  history: createWebHistory(import.meta.env.VITE_BASE_URL),
  routes: allRoutes,
  scrollBehavior() {
    return {
      el: '#app',
      top: 0,
      behavior: 'smooth',
    };
  },
});

router.beforeEach((to, from, next) => {
  console.log(from);
  const token = localStorage.getItem('token');
  if (to.meta.requiresAuth && !token) {
    next({ path: '/login' });
  } else {
    next();
  }
});

export default router;
